﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

using ScrumTable.Common;
using ScrumTable.Common.Collections;
using ScrumTable.Common.Logging;
using ScrumTable.Common.Monitoring;
using ScrumTable.Common.Net;
using ScrumTable.Common.Security;
using ScrumTable.Common.Text;
using ScrumTable.Common.Threading;
using ScrumTable.DL.Data.Generic.Cache;
using ScrumTable.DL.Data.Schema.ScrumTableV1;
using ScrumTable.DL.Data.TFS.Bulk.Properties;
using ScrumTable.DL.Data.TFS.Bulk.Services.IterationHandling.Serialization;
using ScrumTable.DL.Data.TFS.Services.Reporting;
using ScrumTable.DL.Data.TFS.Services.SharePoint;
using ScrumTable.DL.Data.TFS.Services.TeamFoundation;

#endregion

namespace ScrumTable.DL.Data.TFS.Bulk.Services.IterationHandling
{
    /// <summary>
    /// This class is used to load all data below a given project.
    /// </summary>
    internal class WssIterationLoader : IterationLoaderBase
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new WssIterationLoader with the associated schema config.
        /// </summary>
        /// <param name="schema">Specifies the schema configuration data.</param>
        internal WssIterationLoader(IterationSchema schema)
            : base(schema)
        {
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Loads the iteration data using the strategies of the underlying
        /// derivations.
        /// </summary>
        /// <param name="importMonitor">Specifies the data load monitor which is used to visualize the data import.</param>
        /// <param name="workItemDataLoader">Specifies the work item loader which is used to initialize the CacheWorkItem instances.</param>
        /// <param name="context">Specifies the context with all data which is required to import the data.</param>
        /// <param name="callback">Specifies the callback mechanism method which is used to call the next load part.</param>
        internal override void StartLoadIterationData(IDataImportMonitor importMonitor, WorkItemDataLoader workItemDataLoader, InitialDataCacheLoader.DataLoadContext context, Action<Exception> callback)
        {
            PreCondition.AssertNotNull(importMonitor, "importMonitor");
            PreCondition.AssertNotNull(context, "context");
            PreCondition.AssertNotNull(callback, "callback");

            importMonitor.StartSubProgress(IterationLoadPart);

            try
            {
                LoadIterationData(importMonitor, context);
            }
            catch (Exception e)
            {
                importMonitor.EndSubProgress(IterationLoadPart, e);
                callback(e);
            }

            importMonitor.EndSubProgress(IterationLoadPart);
            callback(null);
        }

        /// <summary>
        /// Loads the iteration nodes from the given data context and returns the created cache iteration
        /// instances.
        /// </summary>
        /// <param name="importMonitor">Specifies the data load monitor which is used to visualize the data import.</param>
        /// <param name="context">Specifies the context with the data providers.</param>
        /// <returns>Returns the created list with iterations.</returns>
        private void LoadIterationData(IDataImportMonitor importMonitor, InitialDataCacheLoader.DataLoadContext context)
        {
            PreCondition.AssertNotNull(importMonitor, "importMonitor");
            PreCondition.AssertNotNull(context, "context");

            List<Node> iterationNodes = new List<Node>();
            LoadIterationsRecursive(iterationNodes, new Dictionary<string, Node>(), context.TfsProject.IterationRootNodes);

            int iterationIndex = 0;

            foreach (Node iteration in iterationNodes)
            {
                string iterationPathName = GetIterationPathName(iteration.Path);
                IterationDate date = GetStartAndEndDate(context, iteration.Id, iterationPathName);
                CacheIteration cacheIteration = context.CacheProject.OwnerContext.ElementFactory.CreateIteration(
                    ObjectUtil.ConvertToString(iteration.Id),
                    iteration.Id,
                    iterationIndex,
                    iterationPathName,
                    iteration.Path,
                    date.StartDate,
                    date.EndDate);

                context.LoadedIterations.Add(cacheIteration);
                importMonitor.ReportProgress(IterationLoadPart, iterationIndex + 1, iterationNodes.Count);
                ++iterationIndex;
            }
        }

        private IterationDate GetStartAndEndDate(InitialDataCacheLoader.DataLoadContext context, int iterationId, string iterationPathName)
        {
            if (context.SharepointContext.IsConnected)
            {
                return GetWssStartAndEndDate(context, iterationId, iterationPathName);
            }
            else
            {
                return GetFileStartAndEndDate(context, iterationId);
            }
        }

        private IterationDate GetFileStartAndEndDate(InitialDataCacheLoader.DataLoadContext context, int iterationId)
        {
            IterationData storeData = context.FileSystemContext.GetData<IterationData>(context.CacheContext.Schema.IterationSchema);
            Iteration foundIteration = null;

            if (storeData.Iterations != null)
            {
                foundIteration = (from iteration in storeData.Iterations
                                  where iteration.IterationId == iterationId
                                  select iteration).FirstOrDefault();
            }

            if (foundIteration != null)
            {
                return new IterationDate
                {
                    EndDate = foundIteration.EndDate,
                    StartDate = foundIteration.StartDate
                };
            }
            return new IterationDate
            {
                EndDate = DateTime.Now,
                StartDate = DateTime.Now
            };
        }

        private IterationDate GetWssStartAndEndDate(InitialDataCacheLoader.DataLoadContext context, int iterationId, string iterationPathName)
        {
            WssIteration wssInformation = context.SharepointContext.GetIterationOrDefault(iterationId, iterationPathName);
            return new IterationDate
            {
                EndDate = wssInformation.EndDate,
                StartDate = wssInformation.StartDate
            };
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        #endregion



        //--------------------------------------------------------------------
        // Nested Classes
        //--------------------------------------------------------------------

        private struct IterationDate
        {
            internal DateTime StartDate { get; set; }
            internal DateTime EndDate { get; set; }
        }
    }
}